package com.shigui.news.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	public static final SessionFactory sessionFactory;

	static {
		Configuration config = new Configuration().configure();
		StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
				.applySettings(config.getProperties());
		StandardServiceRegistry ssr = ssrb.build();
		sessionFactory = config.buildSessionFactory(ssr);
	}

	public static final ThreadLocal session = new ThreadLocal();

	public static Session currentSession() throws HibernateException {
		Session currentSession = (Session) session.get();

		if (currentSession == null) {
			currentSession = sessionFactory.openSession();
			session.set(currentSession);
		}

		return currentSession;
	}

	public static void closeSession() throws HibernateException {
		Session currentSession = (Session) session.get();

		if (currentSession != null) {
			currentSession.close();
		}

		session.set(null);
	}

}
